import os
from dotenv import load_dotenv
from sqlalchemy.orm import Session
from sqlalchemy import select
from ..models.voices_model import Voices
from fastapi import HTTPException
from ..utils.uploads_oss import main as upload_on_oss

load_dotenv()
SOURCES_PATH=os.getenv("SOURCES_PATH")
def get_voice_by_id(db: Session, voice_id: int):
    query=select(Voices).where(Voices.id == voice_id)
    result=db.execute(query).scalars().first()
    return result.as_dict()
def create_voice(db: Session, name: str,path: str, type: int):
    if db.execute(select(Voices).where(Voices.name == name)).scalars().first():
        raise HTTPException(status_code=400, detail=f"Voice {name} already exists")
    file_path=os.path.join(SOURCES_PATH, path)
    upload_on_oss(key=path, file_path=file_path)
    voice=Voices(name=name, path=path, type=type,
                 oss_url="http://whatteam1.oss-cn-beijing.aliyuncs.com/"+ path)
    db.add(voice)
    db.commit()
    db.refresh(voice)
    return voice.as_dict()

def delete_voice_by_id(db: Session, voice_id: int):
    vocie=db.query(Voices).filter(Voices.id == voice_id).first()
    if not vocie:
        raise HTTPException(status_code=404, detail="Voice not found")
    db.delete(vocie)
    db.commit()
    return vocie.as_dict()

def update_voice(db: Session, voice_id: int, name:str=None, path:str=None):
    voice=db.query(Voices).filter(Voices.id == voice_id).first()
    if not voice:
        raise HTTPException(status_code=404, detail="Voice not found")
    if name:
        voice.name=name
    elif path:
        voice.path=path
    elif type:
        voice.type=type

    db.commit()
    db.refresh(voice)
    return voice.as_dict()



# if __name__ == "__main__":
#     from database.db import SessionLocal
#     db = SessionLocal()
